using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using CPlatePrintSys.Domain.DTOs;
using Newtonsoft.Json;

namespace CPlatePrintSys.Application.Services
{
    /// <summary>
    /// CadWin系统图纸信息获取服务
    /// </summary>
    public class CadWinService
    {
        private bool _useLocalTestData = true;

        // 预留API或数据源地址字段
        private string _dataSource;
        public string DataSource
        {
            get => _dataSource;
            set => _dataSource = value;
        }

        public CadWinService(string dataSource = null)
        {
            _dataSource = dataSource;
        }

        /// <summary>
        /// 获取CadWin图纸信息（实际应为接口/文件读取，当前为mock数据）
        /// </summary>
        public async Task<List<CadWinDrawingInfoDto>> GetDrawingInfosAsync()
        {
            await Task.Delay(50); // 模拟异步
            var list = new List<CadWinDrawingInfoDto>();
            for (int i = 26; i <= 50; i++)
            {
                list.Add(new CadWinDrawingInfoDto
                {
                    ShipNo = $"S{i:D3}",
                    LotNo = $"L{i:D3}",
                    PlateNo = $"P{i:D3}",
                    Sequence = $"SEQ{i:D3}",
                    DesignSpecCls = i % 2 == 0 ? "Q390D" : "Q235B",
                    DesignSpecThickness = 12 + i % 4,
                    DesignSpecLength = 8500 + i * 8,
                    DesignSpecWidth = 2100 + i * 3,
                    DxfPath = $@"D:\\CadWin\\S{i:D3}\\L{i:D3}\\P{i:D3}.dxf"
                });
            }
            if (_useLocalTestData)
            {
                return LoadLocalMockData();
            }
            return list;
        }

        /// <summary>
        /// 从MockData文件夹加载本地数据
        /// </summary>
        public List<CadWinDrawingInfoDto> LoadLocalMockData()
        {
            try
            {
                // 获取应用程序所在目录
                string appDirectory = AppDomain.CurrentDomain.BaseDirectory;

                // 构建MockData\AM\AMData.json的完整路径
                string mockDataPath = Path.Combine(appDirectory, "MockData", "CadWin", "CadWinData.json");

                // 检查文件是否存在
                if (!File.Exists(mockDataPath))
                {
                    throw new FileNotFoundException($"Mock数据文件未找到: {mockDataPath}");
                }

                // 读取JSON文件内容
                string jsonContent = File.ReadAllText(mockDataPath);

                // 反序列化为DxfDrawingInfoDto列表
                var drawingInfos = JsonConvert.DeserializeObject<List<CadWinDrawingInfoDto>>(jsonContent);

                // 处理DxfPath路径
                foreach (var drawingInfo in drawingInfos)
                {
                    if (!string.IsNullOrEmpty(drawingInfo.DxfPath))
                    {
                        // 检查DxfPath是否为合法路径
                        if (!Path.IsPathRooted(drawingInfo.DxfPath) || !File.Exists(drawingInfo.DxfPath))
                        {
                            // 如果不是合法路径，则使用当前目录+文件名形成新的DxfPath
                            string fileName = Path.GetFileName(drawingInfo.DxfPath);
                            if (!string.IsNullOrEmpty(fileName))
                            {
                                drawingInfo.DxfPath = Path.Combine(appDirectory, "MockData", "CadWin", fileName);
                            }
                        }
                    }
                }

                return drawingInfos;
            }
            catch (Exception ex)
            {
                // 记录错误日志（这里可以根据需要添加日志记录）
                throw new InvalidOperationException($"加载本地Mock数据失败: {ex.Message}", ex);
            }
        }
    }
} 